package com.xxx.blog.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.blog.domain.Article;
import com.xxx.blog.query.ArticleQuery;
import com.xxx.blog.service.IArticleService;
import com.xxx.blog.vo.AchieveVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
@Api(tags = "文章接口类")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<Article>> findAll() {
        List<Article> articles = articleService.findAll();
        return R.ok(articles);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public R<Article> findById(@PathVariable long id) {
        Article article = articleService.findById(id);
        return R.ok(article);
    }

    @PostMapping
    @ApiOperation(value = "分页条件查询")
    public  PageInfo<Article> queryPage(@RequestBody ArticleQuery articleQuery) {
        List<Article> list = articleService.queryPage(articleQuery);
        return new PageInfo<Article>(list);
    }

    @PutMapping
    @ApiOperation(value = "增加或者修改")
    public R<Void> addOrUpdateArticle(@RequestBody Article article) {
        try {
            Long id = article.getId();
            if (id == null) {
                articleService.addArticle(article);
            } else {
                articleService.updateArticle(article);
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("文章类型添加失败");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除一个文章类型")
    public R<Void> deleteArticle(@PathVariable Long id) {
        try {
            articleService.deleteArticle(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation(value = "批量删除文章类型")
    public R<Void> batchArticle(@RequestBody Long[] ids) {
        try {
            articleService.batchArticle(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("已经存在");
        }
        return R.ok();
    }

    @GetMapping("/achieveVo")
    @ApiOperation(value = "归档博客文章")
    public R<List<AchieveVo>> getAchieveVo() {
        List<AchieveVo> achieveVo = articleService.getAchieveVo();
        return R.ok(achieveVo);
    }

    @GetMapping("/relate/{id}")
    @ApiOperation(value = "相关文章的查询")
    public  List<Article>  getRelate(@PathVariable Long id) {
        List<Article> list = articleService.getRelate(id);
        return list;
    }

}
